﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RAP.Developer.Tools.DebugConsole
{
  public partial class frmMain : Form
  {
    private RemoteDebugClient remoteDebugClient = new RemoteDebugClient();

    public frmMain()
    {
      InitializeComponent();
    }

    private void frmMain_Load(object sender, EventArgs e)
    {
      remoteDebugClient.OnLogArrived += new EventHandler<DebugLogData>(OnLogArrived);
      ConnectServer();
    }

    private void OnLogArrived(object sender, DebugLogData logData)
    {
      WriteLog(logData);
    }

    private void WriteLog(DebugLogData logData)
    {
      if (txtLogs.InvokeRequired)
      {
        txtLogs.BeginInvoke(new Action<DebugLogData>(WriteLog), logData);
      }
      else
      {
        lock (remoteDebugClient)
        {
          if (txtLogs.TextLength > 0)
          {
            txtLogs.SelectionStart = txtLogs.TextLength;
          }
          txtLogs.SelectionColor = Color.FromName(logData.ForegroundColor.ToString());
          txtLogs.AppendText(logData.Msg);
          txtLogs.AppendText("\r\n");
          txtLogs.SelectionStart = txtLogs.TextLength;
          txtLogs.ScrollToCaret();
        }
      }
    }

    private void WriteLog(string logMsg)
    {
      WriteLog(new DebugLogData { Msg = logMsg });
    }

    private void ConnectServer()
    {
      remoteDebugClient.ConnectServer();
    }

    private void DoInputCommand(string cmd)
    {
      WriteLog(cmd);
      switch (cmd.ToLower())
      {
        case "cls":
        case "clear":
          txtLogs.Clear();
          break;

        case "stop":
          remoteDebugClient.Stop();
          break;

        case "connect":
          ConnectServer();
          break;
      }
    }

    private void txtInput_KeyDown(object sender, KeyEventArgs e)
    {
      switch (e.KeyCode)
      {
        case Keys.Enter:
          DoInputCommand(txtInput.Text);
          txtInput.Clear();
          break;
      }
    }

    private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
    {
      remoteDebugClient.Stop();
    }
  }
}
